<?php
session_start();
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}
require_once 'track_online.php';

$currentUser = $_SESSION['username'];
$groupName = $_GET['group_name'] ?? null;

if (!$groupName) {
    die("未指定群聊！");
}

// 定义群聊文件夹和信息文件路径
$qlDir = __DIR__ . '/ql';
$infoFile = $qlDir . '/info.json';

// 检查群聊信息文件是否存在
if (!file_exists($infoFile)) {
    die("群聊信息文件不存在！");
}

// 解析群聊信息文件
$groups = json_decode(file_get_contents($infoFile), true);
if (!is_array($groups)) {
    $groups = [];
}

// 找到匹配的群聊文件夹名
$groupFolder = null;
$groupCreator = null;
$groupAdmins = [];
foreach ($groups as $id => $group) {
    if ($group['name'] === $groupName) {
        $groupFolder = $id;
        $groupCreator = $group['creator'];
        $groupAdmins = $group['admins'] ?? [];
        break;
    }
}

if (!$groupFolder) {
    die("未找到对应的群聊！");
}

// 检查群成员文件路径
$peopleFile = $qlDir . "/$groupFolder/people.json";

// 自动加入群聊功能
function autoJoinGroup($username, $groupFolder, $qlDir) {
    $peopleFile = $qlDir . "/$groupFolder/people.json";
    
    // 如果成员文件不存在，创建并添加用户
    if (!file_exists($peopleFile)) {
        // 确保目录存在
        if (!is_dir(dirname($peopleFile))) {
            mkdir(dirname($peopleFile), 0777, true);
        }
        
        // 创建初始成员列表
        $members = [$username];
        file_put_contents($peopleFile, json_encode($members));
        return true;
    }
    
    // 获取现有成员
    $members = json_decode(file_get_contents($peopleFile), true);
    if (!is_array($members)) {
        $members = [];
    }
    
    // 如果用户不在成员列表中，添加用户
    if (!in_array($username, $members)) {
        $members[] = $username;
        file_put_contents($peopleFile, json_encode($members));
        return true;
    }
    
    return false;
}

// 自动将当前用户加入群聊
autoJoinGroup($currentUser, $groupFolder, $qlDir);

// 获取群成员
$members = [];
if (file_exists($peopleFile)) {
    $members = json_decode(file_get_contents($peopleFile), true);
    if (!is_array($members)) {
        $members = [];
    }
}

// 排序成员：群主 > 管理员 > 普通成员（按字母排序）
$owner = [];
$admins = [];
$normalMembers = [];

foreach ($members as $member) {
    if ($member === $groupCreator) {
        $owner[] = $member;
    } elseif (in_array($member, $groupAdmins)) {
        $admins[] = $member;
    } else {
        $normalMembers[] = $member;
    }
}

// 按字母排序
sort($admins);
sort($normalMembers);

// 合并所有成员
$sortedMembers = array_merge($owner, $admins, $normalMembers);

// 获取普通成员首字母分组
$alphabetGroups = [];
foreach ($normalMembers as $member) {
    $firstChar = mb_substr($member, 0, 1);
    if (preg_match('/^[a-zA-Z]$/', $firstChar)) {
        $firstChar = strtoupper($firstChar);
    } else {
        $firstChar = '#';
    }
    
    if (!isset($alphabetGroups[$firstChar])) {
        $alphabetGroups[$firstChar] = [];
    }
    $alphabetGroups[$firstChar][] = $member;
}

// 按字母顺序排序分组
ksort($alphabetGroups);

// 获取用户头像函数
function getUserAvatar($username) {
    $userInfoFile = __DIR__ . "/user/$username/info.json";
    if (file_exists($userInfoFile)) {
        $userInfo = json_decode(file_get_contents($userInfoFile), true);
        return $userInfo['avatar'] ?? 'default-avatar.png';
    }
    return 'default-avatar.png';
}

// 检查用户是否在线
function isUserOnline($username) {
    $online_file = 'online_users.dat';
    if (!file_exists($online_file)) return false;
    
    $online_users = unserialize(file_get_contents($online_file));
    if (!is_array($online_users)) return false;
    
    return isset($online_users[$username]);
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($groupName) ?> - 群成员列表</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            -webkit-tap-highlight-color: transparent;
        }
        
        body {
            background-color: #f8f9fa;
            color: #333;
            min-height: 100vh;
        }
        
        /* 顶部导航栏 - 白色风格 */
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: #ffffff;
            color: #333;
            padding: 15px 20px;
            display: flex;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            z-index: 100;
            border-bottom: 1px solid #e0e4e9;
        }
        
        .back-btn {
            background: #f0f2f5;
            border: none;
            color: #4e54c8;
            font-size: 18px;
            margin-right: 15px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: #e4e6ff;
            transform: translateX(-3px);
        }
        
        .navbar-title {
            font-size: 18px;
            font-weight: 600;
            flex-grow: 1;
            color: #333;
        }
        
        /* 主内容区 */
        .content {
            margin-top: 70px; /* 导航栏高度 */
            padding: 20px;
            max-width: 800px;
            margin-left: auto;
            margin-right: auto;
            width: 100%;
        }
        
        /* 群名称显示在左上角 */
        .group-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px 0 20px;
            margin-bottom: 20px;
            border-bottom: 1px solid #e0e4e9;
        }
        
        .group-info {
            display: flex;
            flex-direction: column;
        }
        
        .group-name {
            font-size: 24px;
            font-weight: 700;
            color: #2d3748;
            position: relative;
            display: inline-block;
            padding-bottom: 10px;
        }
        
        .group-name::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 60px;
            height: 3px;
            background: linear-gradient(90deg, #4e54c8, #8f94fb);
            border-radius: 3px;
        }
        
        .member-count {
            font-size: 16px;
            color: #718096;
            margin-top: 8px;
        }
        
        /* 搜索框 */
        .search-container {
            position: relative;
            margin-bottom: 20px;
        }
        
        .search-box {
            width: 100%;
            padding: 14px 20px 14px 50px;
            border-radius: 50px;
            border: 1px solid #e0e4e9;
            font-size: 16px;
            background: #ffffff;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
        }
        
        .search-box:focus {
            outline: none;
            border-color: #4e54c8;
            box-shadow: 0 4px 12px rgba(78, 84, 200, 0.15);
        }
        
        .search-icon {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: #718096;
            font-size: 18px;
        }
        
        /* 字母导航 */
        .alphabet-nav {
            position: fixed;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            display: flex;
            flex-direction: column;
            align-items: center;
            z-index: 99;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 20px;
            padding: 10px 5px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .alphabet-link {
            color: #4e54c8;
            font-size: 14px;
            font-weight: 600;
            text-decoration: none;
            padding: 4px 8px;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 2px 0;
            transition: all 0.3s ease;
        }
        
        .alphabet-link:hover {
            background: #4e54c8;
            color: white;
        }
        
        /* 成员列表 */
        .member-list {
            background-color: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
            overflow: hidden;
            border: 1px solid #e0e4e9;
        }
        
        .member-group {
            padding: 15px 0;
        }
        
        .group-header {
            padding: 0 20px 10px;
            font-size: 18px;
            font-weight: 700;
            color: #4e54c8;
            border-bottom: 1px solid #e0e4e9;
            margin-bottom: 10px;
        }
        
        .separator {
            height: 1px;
            background: linear-gradient(90deg, transparent, #e0e4e9, transparent);
            margin: 15px 20px;
        }
        
        .member-item {
            display: flex;
            align-items: center;
            padding: 16px 20px;
            transition: all 0.3s ease;
        }
        
        .member-item:hover {
            background-color: #f8f9fa;
        }
        
        .member-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 15px;
            border: 2px solid #e4e6eb;
            background-color: #f0f2f5;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .member-avatar:hover {
            transform: scale(1.05);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .member-info {
            flex-grow: 1;
        }
        
        .member-name {
            font-size: 17px;
            font-weight: 600;
            color: #2d3748;
            display: flex;
            align-items: center;
        }
        
        /* 群主标识 - 金色 */
        .owner-badge {
            background: linear-gradient(135deg, #ffd700, #ffb700);
            color: #8b7500;
            font-size: 12px;
            padding: 3px 8px;
            border-radius: 20px;
            margin-left: 10px;
            font-weight: bold;
            box-shadow: 0 2px 5px rgba(255, 215, 0, 0.3);
        }
        
        /* 管理员标识 - 蓝色 */
        .admin-badge {
            background: linear-gradient(135deg, #4e54c8, #8f94fb);
            color: white;
            font-size: 12px;
            padding: 3px 8px;
            border-radius: 20px;
            margin-left: 10px;
            box-shadow: 0 2px 5px rgba(78, 84, 200, 0.3);
        }
        
        .member-status {
            font-size: 14px;
            color: #718096;
            margin-top: 5px;
            display: flex;
            align-items: center;
        }
        
        .online-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 6px;
        }
        
        .online {
            background-color: #2ecc71;
            box-shadow: 0 0 6px #2ecc71;
        }
        
        .offline {
            background-color: #95a5a6;
        }
        
        .no-members {
            text-align: center;
            padding: 40px 20px;
            color: #718096;
        }
        
        .no-members i {
            font-size: 48px;
            color: #bdc3c7;
            margin-bottom: 15px;
        }
        
        .no-members p {
            font-size: 18px;
            margin-top: 10px;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .content {
                padding: 15px;
            }
            
            .member-item {
                padding: 14px 15px;
            }
            
            .member-avatar {
                width: 45px;
                height: 45px;
            }
            
            .group-name {
                font-size: 22px;
            }
            
            .alphabet-nav {
                display: none;
            }
        }
        
        @media (max-width: 480px) {
            .navbar {
                padding: 12px 15px;
            }
            
            .back-btn {
                font-size: 16px;
                width: 32px;
                height: 32px;
            }
            
            .navbar-title {
                font-size: 16px;
            }
            
            .content {
                margin-top: 60px;
            }
            
            .group-name {
                font-size: 20px;
            }
            
            .member-avatar {
                width: 40px;
                height: 40px;
            }
            
            .member-name {
                font-size: 16px;
            }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 - 白色风格 -->
    <div class="navbar">
        <button class="back-btn" onclick="history.back()">
            <i class="fas fa-arrow-left"></i>
        </button>
        <div class="navbar-title">群成员列表</div>
    </div>
    
    <!-- 字母导航 -->
    <div class="alphabet-nav">
        <?php foreach (range('A', 'Z') as $letter): ?>
            <a href="#group-<?= $letter ?>" class="alphabet-link"><?= $letter ?></a>
        <?php endforeach; ?>
        <a href="#group-hash" class="alphabet-link">#</a>
    </div>
    
    <!-- 主内容区 -->
    <div class="content">
        <!-- 群名称显示在左上角 -->
        <div class="group-header">
            <div class="group-info">
                <div class="group-name"><?= htmlspecialchars($groupName) ?></div>
                <div class="member-count"><?= count($sortedMembers) ?> 位成员</div>
            </div>
        </div>
        
        <!-- 搜索框 -->
        <div class="search-container">
            <i class="fas fa-search search-icon"></i>
            <input type="text" id="search-input" class="search-box" placeholder="搜索成员名字...">
        </div>
        
        <div class="member-list" id="member-list">
            <?php if (empty($sortedMembers)): ?>
                <div class="no-members">
                    <i class="fas fa-user-friends"></i>
                    <p>当前群聊暂无成员</p>
                </div>
            <?php else: ?>
                <!-- 群主部分 -->
                <?php if (!empty($owner)): ?>
                    <div class="member-group">
                        <div class="group-header">群主</div>
                        <?php foreach ($owner as $member): ?>
                            <div class="member-item" data-name="<?= htmlspecialchars(strtolower($member)) ?>">
                                <a href="userinfo.php?user=<?= urlencode($member) ?>">
                                    <img src="<?= getUserAvatar($member) ?>" alt="头像" class="member-avatar">
                                </a>
                                <div class="member-info">
                                    <div class="member-name">
                                        <?= htmlspecialchars($member) ?>
                                        <span class="owner-badge">群主</span>
                                    </div>
                                    <div class="member-status">
                                        <span class="online-dot <?= isUserOnline($member) ? 'online' : 'offline' ?>"></span>
                                        <?= isUserOnline($member) ? '在线' : '离线' ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                
                <!-- 管理员部分 -->
                <?php if (!empty($admins)): ?>
                    <div class="separator"></div>
                    <div class="member-group">
                        <div class="group-header">管理员</div>
                        <?php foreach ($admins as $member): ?>
                            <div class="member-item" data-name="<?= htmlspecialchars(strtolower($member)) ?>">
                                <a href="userinfo.php?user=<?= urlencode($member) ?>">
                                    <img src="<?= getUserAvatar($member) ?>" alt="头像" class="member-avatar">
                                </a>
                                <div class="member-info">
                                    <div class="member-name">
                                        <?= htmlspecialchars($member) ?>
                                        <span class="admin-badge">管理员</span>
                                    </div>
                                    <div class="member-status">
                                        <span class="online-dot <?= isUserOnline($member) ? 'online' : 'offline' ?>"></span>
                                        <?= isUserOnline($member) ? '在线' : '离线' ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                
                <!-- 普通成员部分 -->
                <?php if (!empty($alphabetGroups)): ?>
                    <div class="separator"></div>
                    <?php foreach ($alphabetGroups as $letter => $groupMembers): ?>
                        <div class="member-group" id="group-<?= $letter ?>">
                            <div class="group-header"><?= $letter ?></div>
                            <?php foreach ($groupMembers as $member): ?>
                                <div class="member-item" data-name="<?= htmlspecialchars(strtolower($member)) ?>">
                                    <a href="userinfo.php?user=<?= urlencode($member) ?>">
                                        <img src="<?= getUserAvatar($member) ?>" alt="头像" class="member-avatar">
                                    </a>
                                    <div class="member-info">
                                        <div class="member-name">
                                            <?= htmlspecialchars($member) ?>
                                        </div>
                                        <div class="member-status">
                                            <span class="online-dot <?= isUserOnline($member) ? 'online' : 'offline' ?>"></span>
                                            <?= isUserOnline($member) ? '在线' : '离线' ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
    
    <script>
        // 成员搜索功能
        const searchInput = document.getElementById('search-input');
        const memberItems = document.querySelectorAll('.member-item');
        
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase().trim();
            
            memberItems.forEach(item => {
                const memberName = item.getAttribute('data-name');
                if (memberName.includes(searchTerm)) {
                    item.style.display = 'flex';
                } else {
                    item.style.display = 'none';
                }
            });
        });
        
        // 平滑滚动到字母分组
        document.querySelectorAll('.alphabet-link').forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const targetId = this.getAttribute('href');
                const targetElement = document.querySelector(targetId);
                
                if (targetElement) {
                    window.scrollTo({
                        top: targetElement.offsetTop - 70,
                        behavior: 'smooth'
                    });
                }
            });
        });
    </script>
</body>
</html>